﻿using IPBoss.Copyright.Entities;
using IPBoss.Copyright.Entities.ViewModel;
using IPBoss.Copyright.Entities.WebSiteModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IPBoss.Copyright.UtilityHelper
{
    public class CookieHelper
    {
        /// <summary>
        /// 获取指定cookie
        /// </summary>
        /// <returns></returns>
        public static System.Net.Cookie GetCc(string cookies, string cookieName)
        {
            System.Net.Cookie cookieCollection = new System.Net.Cookie();
            if (cookies == null)
            {
                return cookieCollection;
            }
            Dictionary<string, System.Net.Cookie> keys = new Dictionary<string, System.Net.Cookie>();
            string[] arr = cookies.Split('$');
            foreach (string s in arr)
            {

                if (string.IsNullOrEmpty(s))
                    continue;
                string[] car = s.Split('^');
                if (car[1] != cookieName)
                    continue;
                cookieCollection.Domain = car[0];
                cookieCollection.Name = car[1];
                cookieCollection.Value = car[2];

            }
            return cookieCollection;
        }
        public static void SetCookie(string cookies, Object userModel)
        {
            if (!string.IsNullOrWhiteSpace(cookies))
            {

                System.Net.Cookie userCookie = CookieHelper.GetCc(cookies, "webUserInfo");
                if (userCookie != null && !string.IsNullOrEmpty(userCookie.Value))
                {
                    if (!Static.CcCookies.Contains(userCookie))
                        Static.CcCookies.Add(userCookie);
                    if (userModel!= null&&!string.IsNullOrEmpty((userModel.ToString())))
                    {
                        Static.WebUserInfo = JsonHelper.Deserialize<WebUserInfo>(userModel.ToString());
                        Log4NetHelper.SetUserID(Static.WebUserInfo.accountName == ConfigHelper.GetAppSetting("SZLoginName") ? ConfigHelper.GetAppSettingInt("SZUserID", 13500) : ConfigHelper.GetAppSettingInt("BJUserID", 13500));

                    }

                    if (Static.UserCardInfo == null)
                    {
                        HttpParameterType parameter = new HttpParameterType();
                        parameter.Url = "https://gateway.ccopyright.com.cn/userServer/person/getPerson/" + Static.WebUserInfo.id + "/chName";
                        string CardInfoResult = HttpHelper.HttpGet(parameter);

                        CopyRightReturnModel CopyRightModel = JsonHelper.Deserialize<CopyRightReturnModel>(CardInfoResult);
                        if(CopyRightModel.data!=null)
                            Static.UserCardInfo = JsonHelper.Deserialize<UserCardInfo>(CopyRightModel.data.ToString());
                    }
                }

            }
        }
    }
}
